import mongoose from 'mongoose'
import { wsSend, house_every_send_conn } from '~/websocket/utils.js'
// socket公共维护的数据，凡是对于house_data的数据有改动的代码都只应该放在这个文件，
export const house_data = {}
export const conn_house_data = {}
import {
  $members,
  $pong
} from '~/websocket/types.js'
import { RandomNumBoth } from '~/websocket/utils.js'
// const house_data = {}
// house_id:{
// status:0,0准备1开始,2计分中，3已结束
// problem:'泪流成河'
// problem_id:1, 做题id
// problem_tip:'山水类的'，
// updatedAt:'',
// members:{
//   openid:{
//   conn:conn,
//   name: String,
//   avatarUrl:String,
//   gender:Number,
//   m_status:Number,// 0准备1猜题，2作画
//   wait_add_score:2,
//   score:Number,

//  },
// }
//

// 记得处理正在作画时离开或者断网的情况

function time() {
  return parseInt(new Date().getTime() / 1000);
}
// 新增房间
export const add_house_id = (id) => {
  house_data[id] = {
    status: 0,
    problem: '',
    problem_id: '',
    problem_tip: '',
    members: {},
    updatedAt: time()
  }
  // 弄一个存储ws的对象，结构一模一样
  conn_house_data[id] = {
    members: {}
  }
}
// 新增成员
export const add_member = ({ house_id, openid, conn, name, avatarUrl, gender }) => {
  house_data[house_id].updatedAt = time();
  house_data[house_id].members[openid] = {
    name,
    draw_data: [],
    avatarUrl,
    gender,
    m_status: 0, // 0准备1猜题，2作画
    score: 0,
    wait_add_score: 0,
    updatedAt: time()
  }
  conn_house_data[house_id].members[openid] = { conn }
}
export const update_member_time = ({ house_id, openid }) => {
  house_data[house_id].updatedAt = time();
  house_data[house_id].members[openid].updatedAt = time()
}
export const update_conn = ({ conn, house_id, openid }) => {
  if (house_data[house_id]) {
    house_data[house_id].updatedAt = time();
    house_data[house_id].members[openid].updatedAt = time()
    conn_house_data[house_id].members[openid].conn = conn;
  }
}

// 定期发送心跳和剔除过期人员
setInterval(() => {
  for (const house_id in house_data) {
    if (house_data[house_id] && time() - house_data[house_id].updatedAt > 90) {
      // 剔除60秒未响应的的房间
      console.log('剔除房间号：' + house_id)
      delete house_data[house_id];
      delete conn_house_data[house_id]
      continue;
    }
    for (const openid in house_data[house_id].members) {
      if (house_data[house_id].members[openid] && time() - house_data[house_id].members[openid].updatedAt > 60) {
        // 剔除超过60秒未响应的成员
        console.log('剔除成员：' + house_data[house_id].members[openid])
        delete house_data[house_id].members[openid]
        delete conn_house_data[house_id].members[openid].conn
        // ws更新成员通知其他人
        house_every_send_conn(house_id, {
          type: $members,
          data: house_data[house_id].members
        })
      } else {
        const conn = conn_house_data[house_id].members[openid].conn;
        wsSend(conn, {
          type: $pong
        })
      }
    }
  }
}, 10000);

// 更新房间状态
export const update_house_status = (house_id, status) => {
  house_data[house_id].status = status
}
// 更新用户状态
export const update_user_status = (house_id, openid, status) => {
  house_data[house_id].members[openid].m_status = status
}
// 清楚掉所有人上一题待加分数字
export const clear_last_data = (house_id) => {
  for (const openid in house_data[house_id].members) {
    house_data[house_id].members[openid].wait_add_score = 0;
    house_data[house_id].members[openid].draw_data = [];
  }
}
// 答对将分数放入待加区，等待游戏结束一并加入
export const join_wait_add_score = ({ house_id, openid, score }) => {
  if( house_data[house_id].members[openid]){
    house_data[house_id].members[openid].wait_add_score = score;
    for (const openid in house_data[house_id].members) {
      // 答对给作画这加1分
      if (house_data[house_id].members[openid].m_status === 2) {
        house_data[house_id].members[openid].wait_add_score += 1;
      }
    }
  }
  
}
export const random_problem = (house_id) => {
  return new Promise(async (reslove) => {
    const random = RandomNumBoth(1, 3279)
    const put_problem = mongoose.model('put_problem')
    console.log('开始读取')
    const data = await put_problem.findOne({problem_id:random}).exec();
    //console.log('数据库读取到的随机题目id:',random,data)
    // const random_arr = ['泪流成河', '美若西施', '金蝉脱壳', '行尸走肉', '百里挑一', '金玉满堂', '背水一战', '霸王别姬', '掌上明珠', '满腹经纶'];
    // const problem = random_arr[(Math.random().toString())[2]]
    // const members = house_data[house_id].members
    house_data[house_id].problem = data.problem
    house_data[house_id].problem_id = data.problem_id
    house_data[house_id].problem_tip = data.problem_tip

    reslove()
  })
}
// 重置房间状态，再来一局
export const reset_house = (house_id) => {
  if (house_data[house_id]) {
    house_data[house_id] = Object.assign({}, house_data[house_id], {
      status: 0,
      problem: '',
      problem_id: '',
      problem_tip: '',
    })
    const members = house_data[house_id].members;
    for (const openid in members) {
      members[openid].m_status = 0
      members[openid].wait_add_score = 0;
      members[openid].score = 0;
      members[openid].draw_data = []
    }
  }
}
